package com.weds.edpf.core.web;

import com.weds.bean.jwt.JwtUtils;
import com.weds.core.annotation.Logs;
import com.weds.core.base.BaseCommPager;
import com.weds.core.base.BaseController;
import com.weds.core.base.BasePageSearch;
import com.weds.core.resp.JsonResult;
import com.weds.core.utils.StringUtils;
import com.weds.edpf.core.entity.AcDepDeleteEntity;
import com.weds.edpf.core.entity.AcDepEntity;
import com.weds.edpf.core.entity.AcDepUserEntity;
import com.weds.edpf.core.service.AcDepDeleteService;
import com.weds.edpf.core.service.AcDepService;
import com.weds.edpf.core.service.AcDepUserService;
import com.weds.edpf.core.service.DevService;
import com.weds.edpf.core.service.GateRealService;
import com.weds.edpf.core.service.NTkqRoomService;
import com.weds.edpf.core.service.WtDevLogService;
import com.weds.edpf.core.service.WtModuleService;
import com.weds.edpf.core.service.XfAcTimeService;
import com.weds.edpf.core.util.CharacterUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author
 * @Description 场所管理接口
 * @Date 2019-10-17
 * @version
 * 新增场所，删除场所，修改场所接口  wangjianqiang 2020/06/12
 */
@RestController
@RequestMapping(value = "/acDep")
@Api(value = "场所管理", description = "场所管理")
public class AcDepController extends BaseController {
    @Resource
    private AcDepService acDepService;

    private Logger log = LogManager.getLogger();

    @Autowired
    HttpServletRequest request;

    @Autowired
    DevService devService;

    @Autowired
    NTkqRoomService NTkqRoomService;

    @Autowired
    GateRealService gateRealService;

    @Autowired
    AcDepDeleteService acDepDeleteService;

    @Autowired
    WtModuleService wtModuleService;

    @Autowired
    WtDevLogService wtDevLogService;

    @Autowired
    XfAcTimeService xfAcTimeService;

    @Autowired
    AcDepUserService acDepUserService;


    /**
     * 删除场所条件判断
     * @param depSerial
     * @return
     */
    @Logs
    @ApiOperation(value = "删除场所条件判断", notes = "删除场所条件判断")
    @RequestMapping(value = "/deleteCondition ", method = RequestMethod.GET)
    public JsonResult<Object> deleteCondition(@RequestParam Integer depSerial) {
        if(depSerial == null){
            return failMsg("参数错误");
        }
        if(depSerial == 10000 || depSerial == 100001){
            return failMsg("系统根场所和默认场所不能删除");
        }
        List<AcDepEntity> acDepEntityList = acDepService.selectDepByParent(depSerial);
        if(acDepEntityList != null && acDepEntityList.size() != 0){
            return failMsg("该场所包含子场所无法删除,请先删除该场所的子场所");
        }

        int roomCount = NTkqRoomService.countDepRoom(depSerial);
        if(roomCount > 0){
            return failMsg("场所内存在会议室或宿舍,请把该场所的所有会议室和宿舍删除,再删除该场所");
        }

        int doorCount = gateRealService.countDepDoor(depSerial);
        if(doorCount > 0){
            return failMsg("场所内存在门,请把该场所的所有门删除,再删除该场所");
        }

        int devCount = devService.countDepDev(depSerial);
        if(devCount > 0){
            return failMsg("场所内存在设备,请把该场所的所有设备删除,再删除该场所");
        }
        return succMsg("具备删除条件");
    }

    /**
     * 删除场所
     * @param depSerial
     * @return
     */
    @Logs
    @ApiOperation(value = "删除场所", notes = "删除场所")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public JsonResult<Object> delete(@RequestParam Integer depSerial) {
        if(depSerial == null){
            return failMsg("参数错误");
        }
        if(depSerial == 10000 || depSerial == 100001){
            return failMsg("系统根场所和默认场所不能删除");
        }
        List<AcDepEntity> acDepEntityList = acDepService.selectDepByParent(depSerial);
        if(acDepEntityList != null && acDepEntityList.size() != 0){
            return failMsg("该场所包含子场所无法删除,请先删除该场所的子场所");
        }

        int roomCount = NTkqRoomService.countDepRoom(depSerial);
        if(roomCount > 0){
            return failMsg("场所内存在会议室或宿舍,请把该场所的所有会议室和宿舍删除,再删除该场所");
        }

        int doorCount = gateRealService.countDepDoor(depSerial);
        if(doorCount > 0){
            return failMsg("场所内存在门,请把该场所的所有门删除,再删除该场所");
        }

        int devCount = devService.countDepDev(depSerial);
        if(devCount > 0){
            return failMsg("场所内存在设备,请把该场所的所有设备删除,再删除该场所");
        }
        AcDepEntity acDepEntity = acDepService.selectByPrimaryKey(depSerial);
        if(acDepEntity == null){
            return failMsg("未找到对应场所");
        }

        //插入删除日志
        AcDepDeleteEntity delEntity = new AcDepDeleteEntity();
        delEntity.setDepSerial(depSerial);
        delEntity.setDepParent(acDepEntity.getDepParent());
        delEntity.setDepOrder(acDepEntity.getDepOrder());
        delEntity.setDepName(acDepEntity.getDepName());
        delEntity.setDepNo(acDepEntity.getDepNo());
        delEntity.setDepRule(acDepEntity.getDepRule());
        delEntity.setSj(new Date());
        delEntity.setModuleId(acDepEntity.getModuleId());
        delEntity.setDepType(acDepEntity.getDepType());
        delEntity.setDepState(acDepEntity.getDepState());
        delEntity.setDepLx(acDepEntity.getDepLx());
        delEntity.setDepPlace(acDepEntity.getDepPlace());
        delEntity.setDepSex(acDepEntity.getDepSex());
        delEntity.setDepFloor(acDepEntity.getDepFloor());
        delEntity.setDepNumber(acDepEntity.getDepNumber());
        delEntity.setDtAcType(2);
        acDepDeleteService.insert(delEntity);

        //当前目录其他场所 dep_no 和 dep_order 变更
        List<AcDepEntity> list = acDepService.moreThanOrder(acDepEntity.getDepParent(),acDepEntity.getDepOrder());
        acDepService.depPlaceReOrder(list,depSerial,-1);

        String glyNo = JwtUtils.getJwtData(request).getString("userSerial");
        wtDevLogService.insertLog(2,0,0,"0025","删除场所: " + depSerial + "=" +acDepEntity.getDepName() ,request.getRemoteAddr(),glyNo);

        //删除
        acDepService.deleteByPrimaryKey(depSerial);

        return succMsg("操作成功");
    }


    /**
     * 新增场所
     * @param record
     * @return
     */
    @Logs
    @ApiOperation(value = "新增场所信息", notes = "新增场所信息")
    @RequestMapping(value = "/insertPlace", method = RequestMethod.POST)
    public JsonResult<Object> insertPlace(@RequestBody @Valid AcDepEntity record) {
        if(record == null){
            return failMsg("参数错误");
        }
        Integer depParent = record.getDepParent();
        if(depParent == null || depParent == 0){
            return failMsg("选择要新增的上级场所");
        }
        if(depParent == 100001){
            return failMsg("默认场所下不能新增");
        }

        AcDepEntity acDepEntity = acDepService.selectSameName(depParent,record.getDepName());
        if(acDepEntity != null){
            return failMsg("同及内场所名称重复,请重新输入场所名称");
        }
        int parentPlaceCount = acDepService.countDepPlaceByParent(depParent);
        if (parentPlaceCount >= 1296) {
            return failMsg("此级场所数超过最大上限");
        }

        AcDepEntity parentEntity = acDepService.selectByPrimaryKey(depParent);
        if(parentEntity == null){
            return failMsg("上级场所不存在");
        }
        String parentDepNo = parentEntity.getDepNo();
        if(parentDepNo.length() >= 41){
            return failMsg("场所最多有20个层级");
        }
        String depSerial = wtModuleService.selectModulePlace();
        record.setDepSerial(Integer.parseInt(depSerial));

        if(record.getDepOrder() == null || record.getDepOrder() >= parentPlaceCount){
            record.setDepOrder(parentPlaceCount);
        }
        //插入在中间
        if(record.getDepOrder() != parentPlaceCount){
            //后边的部门更新
            List<AcDepEntity> list = acDepService.moreThanOrder(depParent,record.getDepOrder());
            acDepService.depPlaceReOrder(list, 0,1);
        }
        String d = CharacterUtil.DeciamlToThirtySix(record.getDepOrder().intValue());
        if(d.length() == 1){
            d = "0" + d;
        }
        record.setDepNo(parentDepNo + d);
        record.setSj(new Date());
        record.setModuleId("0025");
        record.setDepNumber(record.getDepNo());
        record.setOldDepNo(record.getDepNo());
        acDepService.insertSelective(record);


        String glyNo = JwtUtils.getJwtData(request).getString("userSerial");
        //插入场所消费默认时段
        xfAcTimeService.insertLog(Integer.parseInt(depSerial),glyNo);
        //插入日志
        wtDevLogService.insertLog(0,0,0,"0025","新增场所: " + depSerial + "=" +record.getDepName() ,request.getRemoteAddr(),glyNo);

        return succMsg("操作成功");
    }

    /**
     * 修改场所信息
     * @param record
     * @return
     */
    @Logs
    @ApiOperation(value = "修改场所信息", notes = "修改场所信息")
    @RequestMapping(value = "/updateDepPlace", method = RequestMethod.POST)
    public JsonResult<Object> updateDepPlace(@RequestBody @Valid AcDepEntity record) {

        boolean paramCheck = record == null || record.getDepSerial() == null || record.getDepSerial() == 0
                || record.getDepParent() == null || record.getDepParent() == 0;
        if (paramCheck) {
            return failMsg("参数错误");
        }
        Integer depSerial =  record.getDepSerial();
        if(depSerial == 10000 || depSerial == 100001){
            return failMsg("系统根场所和默认场所不能修改");
        }
        if(record.getDepParent() == null || record.getDepParent() == 0 || record.getDepParent() == 100001){
            return failMsg("上级场所参数错误");
        }

        AcDepEntity acDepEntity = acDepService.selectByPrimaryKey(depSerial);
        if(acDepEntity == null){
            return failMsg("未找到对应场所");
        }
        //所在目录 修改
        if(!record.getDepParent().equals(acDepEntity.getDepParent())){
            //新目录同级部门 重排序
            int childDepCount = acDepService.countDepPlaceByParent(record.getDepParent());
            if(record.getDepOrder() == null || childDepCount == 0 ){
                record.setDepOrder(childDepCount);
            }else if(record.getDepOrder() > childDepCount){
                record.setDepOrder(childDepCount-1);
            }
            //插入在中间或前边
            if(record.getDepOrder() != childDepCount){
                List<AcDepEntity> list2 = acDepService.moreThanOrder(record.getDepParent(), record.getDepOrder());
                acDepService.depPlaceReOrder(list2,depSerial,1);
            }
            //原同级目录 重排序
            List<AcDepEntity> list1 = acDepService.moreThanOrder(acDepEntity.getDepParent(),acDepEntity.getDepOrder());
            acDepService.depPlaceReOrder(list1,depSerial,-1);

            String d = CharacterUtil.DeciamlToThirtySix(record.getDepOrder());
            if(d.length() == 1){
                d = "0" + d;
            }
            AcDepEntity acDepEntity1 = acDepService.selectByPrimaryKey(record.getDepParent());
            String  depNo = acDepEntity1.getDepNo();
            String newDepNo = depNo + d;
            record.setDepNo(newDepNo);

            //处理当前场所子场所的 depNo 变更
            acDepService.childDepPlaceUpdate(depSerial,newDepNo,0);

        }else if(!acDepEntity.getDepOrder().equals(record.getDepOrder())){
            //重排序
            int childDepCount = acDepService.countDepPlaceByParent(acDepEntity.getDepParent());

            if(record.getDepOrder() == null || childDepCount == 0 ){
                record.setDepOrder(childDepCount);
            }else if(record.getDepOrder() >= childDepCount){
                record.setDepOrder(childDepCount-1);
            }
            int up ;
            List<AcDepEntity> list2 ;
            int from ;
            int end ;
            if(record.getDepOrder() < acDepEntity.getDepOrder()){
                from = record.getDepOrder();
                end = acDepEntity.getDepOrder();
                up = 1;
            }else{
                from = acDepEntity.getDepOrder();
                end = record.getDepOrder();
                up = -1;
            }
            list2 = acDepService.selectListBetwweenOrder(acDepEntity.getDepParent(),from,end);
            acDepService.depPlaceReOrder(list2,depSerial,up);

            String d = CharacterUtil.DeciamlToThirtySix(record.getDepOrder());
            if(d.length() == 1){
                d = "0" + d;
            }
            String  depNo = acDepEntity.getDepNo();
            String newDepNo = depNo.substring(0,depNo.length() -2) + d;
            record.setDepNo(newDepNo);

            //处理当前场所子场所的 depNo 变更
            acDepService.childDepPlaceUpdate(depSerial,newDepNo,0);

        }

        if (StringUtils.isNotBlank(record.getDepName()) && !acDepEntity.getDepName().equals(record.getDepName())) {
            //更新白名单中场所名称
            AcDepUserEntity entity = new AcDepUserEntity();
            entity.setDepLname(record.getDepName());
            entity.setDepSerial(depSerial);
            acDepUserService.updateDepName(entity);
        }
        String glyNo = JwtUtils.getJwtData(request).getString("userSerial");
        wtDevLogService.insertLog(1,0,0,"0025","修改场所: " + depSerial + "=" +record.getDepName() ,request.getRemoteAddr(),glyNo);

        //更新
        acDepService.updateByPrimaryKeySelective(record);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "新增AcDep信息", notes = "新增AcDep信息")
    @RequestMapping(value = "/insert", method = RequestMethod.PUT)
    public JsonResult<Object> insert(@RequestBody @Valid AcDepEntity record) {
        acDepService.insertSelective(record);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "更新AcDep信息", notes = "更新AcDep信息")
    @RequestMapping(value = "/updateByPrimaryKey", method = RequestMethod.POST)
    public JsonResult<Object> updateByPrimaryKey(@RequestBody @Valid AcDepEntity record) {
        acDepService.updateByPrimaryKeySelective(record);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "查询AcDep清单", notes = "查询AcDep清单")
    @RequestMapping(value = "/selectListPageByEntity", method = RequestMethod.POST)
    public JsonResult<BaseCommPager<AcDepEntity>> selectListPageByEntity(@RequestBody BasePageSearch<AcDepEntity> record) {
        setPageHelper(record);
        AcDepEntity entity = record.getSearch();
        if (entity == null) {
            entity = new AcDepEntity();
        }
        List<AcDepEntity> list = acDepService.selectListByEntity(entity);
        return succMsgData(new BaseCommPager<AcDepEntity>(list));
    }


    @Logs
    @ApiOperation(value = "查询AcDep列表", notes = "查询AcDep列表")
    @RequestMapping(value = "/selectListByEntity", method = RequestMethod.POST)
    public JsonResult<List<AcDepEntity>> selectListByEntity(@RequestBody AcDepEntity record) {
        List<AcDepEntity> list = acDepService.selectListByEntity(record);
        return succMsgData(list);
    }

    @Logs
    @ApiOperation(value = "查询AcDep列表", notes = "查询AcDep列表")
    @RequestMapping(value = "/selectDinePlace", method = RequestMethod.GET)
    public JsonResult<List<AcDepEntity>> selectDinePlace() {
        List<AcDepEntity> list = acDepService.selectDinePlace();
        return succMsgData(list);
    }

    @Logs
    @ApiOperation(value = "删除AcDep信息", notes = "删除AcDep信息")
    @RequestMapping(value = "/deleteByPrimaryKey", method = RequestMethod.DELETE)
    public JsonResult<Object> deleteByPrimaryKey(@RequestParam Integer depSerial) {
        acDepService.deleteByPrimaryKey(depSerial);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "查询AcDep信息", notes = "查询AcDep信息")
    @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.GET)
    public JsonResult<AcDepEntity> selectByPrimaryKey(@RequestParam Integer depSerial) {
        AcDepEntity entity = acDepService.selectByPrimaryKey(depSerial);
        return succMsgData(entity);
    }


    @Logs
    @ApiOperation(value = "批量删除AcDep信息", notes = "批量删除AcDep信息")
    @RequestMapping(value = "/deleteBatchByKeys", method = RequestMethod.POST)
    public JsonResult<Object> deleteBatchByKeys(@RequestBody List<AcDepEntity> list) {
        List<AcDepEntity> delList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            delList.add(list.get(i));
            if (delList.size() == 20 || i == list.size() - 1) {
                acDepService.deleteBatchByKeys(delList);
                delList.clear();
            }
        }
        return succMsg();
    }


    @Logs
    @ApiOperation(value = "获取所有餐厅场所信息", notes = "获取所有餐厅场所信息")
    @RequestMapping(value = "/selectAllDep", method = RequestMethod.GET)
    public JsonResult<Object> selectAllDep(){
        List<AcDepEntity> list = acDepService.selectAllDep();
        return succMsgData(list);
    }

}